package com.lihaozhe.service;

import com.lihaozhe.util.string.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author 李昊哲
 * @version 1.0
 * 2021/12/10 下午1:55
 */
@Slf4j
@RequiredArgsConstructor
@Service("userDetailsService")
public class UserService implements UserDetailsService {
    private final PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("获取的账号 >>> {}", username);
        // 1、擦好像数据库中判断账号是否存在如果不存在则抛出UsernameNotFoundException异常
        if (StringUtil.isBlank(username) || !username.equals("lhz")) {
            throw new UsernameNotFoundException("账号不存在");
        }
        // 2、根据账号查询到的密码（注册是已经加密过）进行解析，或者直接把账号密码放入构造方法
        String password = passwordEncoder.encode("123456");
        //  AuthorityUtils.commaSeparatedStringToAuthorityList(该用户拥有的角色列表 多个角色之间使用都好间隔)
        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin, normal"));
    }
}